package pqt;


import java.awt.Component;
import java.awt.Font;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.imageio.ImageIO;
import javax.swing.AbstractCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;



import java.awt.Color;
import java.util.EventObject;

public class VisorAtributos{

	private final JPanel contentPanel;
	private JTable table;
	private DefaultTableModel tableModel;
	List lista = new List();
	private Bloque bloque;
	private String idAtributo;
	private EnsayoAtributos padre;
	final JButton btnAceptar = new JButton("");
	private int anchoFrame;
	private int altoFrame;
	JButton btnMarcarTodas = new JButton("");
	private KeyAdapter keyAdapter;
	
	public VisorAtributos(Bloque bloque,EnsayoAtributos padre, JPanel panel) {
		
		this.bloque = bloque;
		this.padre = padre;
		contentPanel = panel;
		for(int i=0;i<bloque.getAtributosCount();i++)
		lista.add(bloque.getNombreAtributo(i));
		
		mostrarAtributos();
	}
	
	public void mostrarAtributos() {
		
				
		int altoPantalla = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
		int anchoPantalla = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
		anchoFrame = (int)(anchoPantalla*0.6);
		altoFrame = (int)(altoPantalla*0.77);
		
		JLabel tituloEnsayo = new JLabel();
		tituloEnsayo.setBounds(5, 5, contentPanel.getWidth()-10, 50);
		tituloEnsayo.setHorizontalAlignment(SwingConstants.CENTER);
		tituloEnsayo.setOpaque(true);
		tituloEnsayo.setBackground(SystemColor.activeCaption);	
		tituloEnsayo.setFont(new Font("Tahoma", Font.PLAIN, 40));
		tituloEnsayo.setText(bloque.getNombre());
		contentPanel.add(tituloEnsayo);
		
		
		tableModel = new DefaultTableModel(new Object[]{"Atributo", "Estado"},0);
		table = new JTable(tableModel);
		table.setRowHeight(30);
		table.getColumn("Estado").setCellRenderer(new BooleanIconRenderer());
		table.getColumn("Estado").setCellEditor(new BooleanIconEditor());
		table.getColumnModel().getColumn(0).setPreferredWidth(700);
		
		table.getColumn("Atributo").setCellEditor(new MyModel());
		table.setFont(new Font("Tahoma", Font.PLAIN, 20));
		
		for(int i=0;i<lista.getItemCount();i++){
			 tableModel.addRow(new Object[]{lista.getItem(i).toString(), true});
		 }
		
		table.setCellSelectionEnabled(true);
		table.setColumnSelectionAllowed(false);
		
		keyAdapter = new KeyAdapter()
		{
		  public void keyPressed(KeyEvent e)
		  {
			  if(e.getKeyCode() == KeyEvent.VK_ENTER){
				   
				   //if(table.getSelectedRow() == table.getRowCount()-1){
				    	e.consume();
				    	btnAceptar.doClick();
				    //}
				    //btnAceptar.requestFocus();
				   
			   }
			   
			   
			   if(e.getKeyCode() == KeyEvent.VK_SPACE){   
				   
				   if ((boolean) table.getValueAt(table.getSelectedRow(),1)) 
					   table.setValueAt(false, table.getSelectedRow(), 1);
				   else
					   table.setValueAt(true, table.getSelectedRow(), 1);
				    
				}
			   
			   if(e.getKeyCode() == KeyEvent.VK_F1){
					
				   btnMarcarTodas.doClick();
			   }
		  }
		};
		
		table.addKeyListener(keyAdapter);
		
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setBounds(5, 70, anchoFrame-10, 300);
		scrollPane.setBackground(Color.white);
		contentPanel.add(scrollPane);
				
		
		btnAceptar.setFocusable(true);
		btnAceptar.setContentAreaFilled(false);
		btnAceptar.setBorderPainted(false);
		btnAceptar.setBorder(null);
		btnAceptar.setBounds((contentPanel.getWidth()/2)-135, contentPanel.getHeight()-100, 265, 75);
		btnAceptar.setIcon(new ImageIcon(VisorAtributos.class.getResource("/img/AceptarVerdeChico.png")));
		//btnAceptar.setPressedIcon(new ImageIcon(PuestaCero.class.getResource("/img/AceptarNegroChico.png")));
		
		btnAceptar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				imprimirTodos();
				padre.siguienteAtributo();		
				table.removeKeyListener(keyAdapter);
			}
		});
		
		
		contentPanel.add(btnAceptar);
		
		
		btnMarcarTodas.setFocusable(true);
		btnMarcarTodas.setContentAreaFilled(false);
		btnMarcarTodas.setBorderPainted(false);
		btnMarcarTodas.setBorder(null);
		btnMarcarTodas.setIcon(new ImageIcon(VisorAtributos.class.getResource("/img/marcarTodasOk.png")));
		btnMarcarTodas.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				marcarTodas();
			}
		});
		
		btnMarcarTodas.setBounds(10, 380, 230, 65);
		contentPanel.add(btnMarcarTodas);
		
		table.requestFocus();
		if(lista.getItemCount()>0)
			table.setRowSelectionInterval(0, 0);
		//getContentPane().add(scrollPane, BorderLayout.CENTER);
		//contentPanel.getRootPane().setDefaultButton(btnAceptar);
		//btnAceptar.requestFocus();
	}

	
		
	private void imprimirTodos() {
	
		   for (int i = 0; i < table.getRowCount(); i++) {
		    
		     if ((boolean) table.getValueAt(i,1)) {
		    	 SelectorFallas error = new SelectorFallas(bloque,i,bloque.getNombreAtributo(i));
		    }
		   }
	}
	
	private void marcarTodas() {
		 for (int i = 0; i < table.getRowCount(); i++) {
			    
		     table.setValueAt(false, i, 1);
		   }
	}
	
	
	public String getId() {
		return idAtributo;
	}

	 @SuppressWarnings("serial")											//implements TableCellRenderer
	    private class BooleanIconRenderer extends DefaultTableCellRenderer  {

	        @Override
	        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
	                                                                        boolean hasFocus, int row, int col) {
	            String iconFilename = null;
	            
	            if ((boolean) value) {
	                iconFilename = "/img/notaMal.png";
	                value = true;
	            } else {
	                iconFilename = "/img/notaOk.png";
	                value = false;
	            }
	            try {
	                setIcon(new ImageIcon(ImageIO.read(BooleanIconRenderer.class.getResourceAsStream(iconFilename))));
	            } catch (Exception e) {
	                System.err.println("Failed to load the icon.");
	            }
	            if (isSelected) {
	                this.setBackground(Color.white);
	            } else {
	                this.setBackground(Color.white);
	            }
	           // table.getSelectionModel().clearSelection();
	            return this;
	        }
	        
	       
	    }

	    @SuppressWarnings("serial")
	    private class BooleanIconEditor extends AbstractCellEditor implements TableCellEditor, MouseListener {

	        private BooleanComponent boolComp;

	        public BooleanIconEditor() {
	            boolComp = new BooleanComponent(false);
	            boolComp.addMouseListener(this);
	        }

	        @Override
	        public Object getCellEditorValue() {
	            return boolComp.getValue();
	        }

	        @Override
	        public Component getTableCellEditorComponent(JTable table,
	                Object value, boolean isSelected, int row, int column) {
	            boolComp.setValue(! (boolean) value);
	            return boolComp;
	        }

	        @Override
	        public void mouseClicked(MouseEvent e) {
	            this.fireEditingStopped();
	        }

	        @Override
	        public void mousePressed(MouseEvent e) {
	        	
	            this.fireEditingStopped();

	        }
	        public boolean isCellEditable(EventObject e) {
	            return (e instanceof MouseEvent);
	        }
	        @Override
	        public void mouseReleased(MouseEvent e) {
	            this.fireEditingStopped();
	        }

	        @Override
	        public void mouseEntered(MouseEvent e) {
	            this.fireEditingStopped();
	        }

	        @Override
	        public void mouseExited(MouseEvent e) {
	            this.fireEditingStopped();
	        }

			

	    }

	    @SuppressWarnings("serial")
	    private class BooleanComponent extends JComponent {
	        private boolean value;

	        public BooleanComponent(boolean value) {
	            this.value = value;
	        }

	        public boolean getValue() {
	            return value;
	        }

	        public void setValue(boolean value) {
	            this.value = value;
	        }
	    }
	    
	    public class MyModel implements TableCellEditor {
	    	
	    	
	    	
	    	public boolean isCellEditable(int row, int col) {
	    		
	    		System.out.println(tableModel.getValueAt(row, col).toString());
	    		if(tableModel.getValueAt(row, col).toString().equalsIgnoreCase("otros"))
	    		return true;
	    		else
	    			return false;
	    	}

			@Override
			public void addCellEditorListener(CellEditorListener arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void cancelCellEditing() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public Object getCellEditorValue() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public boolean isCellEditable(EventObject arg0) {
				// TODO Auto-generated method stub
				return true;
			}

			@Override
			public void removeCellEditorListener(CellEditorListener arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public boolean shouldSelectCell(EventObject arg0) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean stopCellEditing() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public Component getTableCellEditorComponent(JTable arg0, Object arg1,
					boolean arg2, int arg3, int arg4) {
				// TODO Auto-generated method stub
				return null;
			}
	    }

		
	
	
}